package middle;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution_40 {

    /*private boolean[] visited;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        visited = new boolean[candidates.length];
        List<List<Integer>> res = new ArrayList<>();
        dps(candidates, res, new ArrayList<>(), target, 0);
        return res;
    }

    private void dps(int[] candidates, List<List<Integer>> res, List<Integer> list, int sub, int index) {
        if (sub == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (i > 0 && candidates[i - 1] == candidates[i] && !visited[i - 1]) {
                continue;
            }
            if (candidates[i] > sub) {
                break;
            }
            visited[i] = true;
            list.add(candidates[i]);
            dps(candidates, res, list, sub - candidates[i], i + 1);
            list.remove(list.size() - 1);
            visited[i] = false;
        }
    }*/

    // 网友解题思路
    private List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<Integer> path = new ArrayList<>();
        backtrack(path,candidates,target,0,0);
        return res;
    }

    private void backtrack(List<Integer> path,int[] candidates,int target,int sum,int begin) {
        if(sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = begin;i < candidates.length;i++) {
            if(i > begin && candidates[i] == candidates[i-1]) continue;
            int rs = candidates[i] + sum;
            if(rs <= target) {
                path.add(candidates[i]);
                backtrack(path,candidates,target,rs,i+1);
                path.remove(path.size()-1);
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        Solution_40 model = new Solution_40();
//        List<List<Integer>> lists = model.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
        List<List<Integer>> lists = model.combinationSum2(new int[]{2,5,2,1,2}, 5);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}
